package com.bytz.modules.system.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.bytz.modules.system.dto.EmailDto;
import com.bytz.modules.system.dto.SmsDto;
import com.bytz.modules.system.service.INotifyService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.Map;

@Service
public class NotifyServiceImpl implements INotifyService {
	private static final Logger logger = LoggerFactory.getLogger(NotifyServiceImpl.class);

	/**
	* freemarker配置
	 */
	@Autowired
	private Configuration configuration;

	@Value("${bytz.mail.settings}")
	private String mailSettings;

	private MailAccount mailAccount;
	
	@PostConstruct
	public void init() {
		mailAccount = new MailAccount(mailSettings);
	}

	@Override
	public void sendEmail(EmailDto mail) throws Exception {
		String content;
		if (StrUtil.isNotBlank(mail.getTemplate())) {
			content = doTemplate(mail.getTemplate(), mail.getTemplateParameters());
		} else {
			content = mail.getContent();
		}

		logger.info("发送邮件：{}", content);

		File[] attachments = new File[0];
		if (mail.getAttachments() != null) {
			attachments = mail.getAttachments().toArray(new File[]{});
		}

		MailUtil.send(mailAccount, mail.getTos(), mail.getCcs(), mail.getBCcs(),
				mail.getSubject(), content, mail.getImageMap(), BooleanUtil.isTrue(mail.getHtml()),
				attachments);
	}

	@Override
	public void sendSms(SmsDto sms) throws Exception {
		String content;
		if (StrUtil.isNotBlank(sms.getTemplate())) {
			content = doTemplate(sms.getTemplate(), sms.getTemplateParameters());
		} else {
			content = sms.getContent();
		}

		logger.info("发送短信：{}", content);
		// 实现发短信
	}

	/**
	 * 用模板生成内容
	 */
	private String doTemplate(String template, Map<String, Object> parameters) throws Exception {
		Template t = configuration.getTemplate(template);
		return FreeMarkerTemplateUtils.processTemplateIntoString(t, parameters);
	}
}
